package com.webserver.core;

import com.webserver.controller.ArticleController;
import com.webserver.controller.UserController;
import com.webserver.http.HttpContext;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理请求环节
 */
public class DispatcherServlet {
    private static Logger log = Logger.getLogger(UserController.class);

    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, InvocationTargetException, IllegalAccessException {
        String path = request.getRequestURI();
        log.info("请求路径:"+path);
        /*
            添加了2个注解 @Controller(标注文章和用户) @RequestMapping(标注各种方法,并通过参数传递请求路径)
            利用HandlerMapping类来完成自动读取注解的方法
         */
        //判断该请求路径是否为一个业务
        HandlerMapping.MethodMapping mm = HandlerMapping.getMethodMapping(path);
        if (mm!=null){//当路径对应的请求不为空时
            mm.getMethod().invoke(mm.getController(),request,response);
        }else{
            File file = new File("./webapps"+path);
            if(file.isFile()){//如果用户请求的是一个文件
                response.setEntity(file);
            }else{//否则发送404页面
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
                file = new File("./webapps/root/404.html");
                response.setEntity(file);
            }
            response.putHeader("Server","WebServer");
        }
    }
}
